<template>
  <div class="space-y-6">
    <el-card class="shadow-sm">
      <template #header>
        <div class="flex items-center justify-between">
          <span class="text-xl font-semibold text-gray-800">角色管理</span>
          <el-button
            v-permission="'role:create'"
            type="primary"
            @click="handleAdd"
            class="px-4 py-2"
          >
            <el-icon class="mr-1">
              <Plus />
            </el-icon>新增角色
          </el-button>
        </div>
      </template>

      <!-- 搜索表单 -->
      <DictStatusSearch
        dict-code="sys_status"
        :initial-form="{ name: '', code: '' }"
        @search="handleSearch"
        @reset="handleReset"
      >
        <template #prepend="{ searchForm, updateSearchForm }">
          <el-form-item label="角色名称">
            <el-input
              :model-value="searchForm.name"
              @update:model-value="updateSearchForm('name', $event)"
              placeholder="请输入角色名称"
              class="w-48"
            />
          </el-form-item>
          <el-form-item label="角色编码">
            <el-input
              :model-value="searchForm.code"
              @update:model-value="updateSearchForm('code', $event)"
              placeholder="请输入角色编码"
              class="w-48"
            />
          </el-form-item>
        </template>
      </DictStatusSearch>

      <!-- 角色表格 -->
      <div class="overflow-x-auto">
        <el-table :data="roleList" v-loading="loading" border style="width: 100%" class="text-sm">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="name" label="角色名称" min-width="120" />
          <el-table-column prop="code" label="角色编码" min-width="120" />
          <el-table-column prop="description" label="角色描述" min-width="180" show-overflow-tooltip />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="{ row }">
              <DictTag
                dict-type="sys_status"
                :value="row.status"
                size="small"
                custom-class="text-xs px-2 py-1"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
            :formatter="tableDateTimeFormatter"
          />
          <el-table-column label="操作" width="280" fixed="right">
            <template #default="{ row }">
              <div class="flex space-x-2">
                <el-button
                  v-permission="'role:update'"
                  type="primary"
                  size="small"
                  @click="handleEdit(row)"
                  class="px-3 py-1"
                >
                  <el-icon class="mr-1">
                    <Edit />
                  </el-icon>编辑
                </el-button>
                <el-button
                  v-permission="'role:list'"
                  type="success"
                  size="small"
                  @click="handleAssignMenus(row)"
                  class="px-3 py-1"
                >
                  <el-icon class="mr-1">
                    <Menu />
                  </el-icon>分配菜单
                </el-button>
                <el-dropdown v-if="hasPermission('role:update') || hasPermission('role:delete')" @command="handleCommand($event, row)">
                  <el-button size="small" class="px-3 py-1">
                    <el-icon>
                      <More />
                    </el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item 
                        v-if="hasPermission('role:update')"
                        command="toggleStatus"
                      >
                        {{ row.status ? '禁用' : '启用' }}
                      </el-dropdown-item>
                      <el-dropdown-item 
                        v-if="hasPermission('role:delete')"
                        command="delete" 
                        divided 
                        class="text-red-600"
                      >
                        删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="mt-6 flex justify-end">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          class="text-sm"
        />
      </div>
    </el-card>

    <!-- 角色表单对话框 -->
    <RoleFormDialog v-model="dialogVisible" :role-data="currentRole" @success="handleSuccess" />

    <!-- 菜单分配对话框 -->
    <MenuAssignDialog
      v-model="menuDialogVisible"
      :role-data="currentRole"
      @success="handleMenuAssignSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { getRoleList, deleteRole, updateRoleStatus } from "@/api/role";
import RoleFormDialog from "@/components/RoleFormDialog.vue";
import MenuAssignDialog from "@/components/MenuAssignDialog.vue";
import DictStatusSearch from "@/components/DictStatusSearch.vue";
import DictTag from "@/components/DictTag.vue";
import { useAuthStore } from "@/stores/auth";
import { tableDateTimeFormatter } from "@/utils/format";
import { Plus, Edit, More, Menu } from "@element-plus/icons-vue";

const loading = ref(false);
const roleList = ref([]);
const dialogVisible = ref(false);
const menuDialogVisible = ref(false);
const currentRole = ref(null);

// 权限检查
const authStore = useAuthStore();
const hasPermission = (permission) => {
  return authStore.hasPermission(permission);
};

const searchForm = reactive({
  name: "",
  code: "",
  status: "",
});

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
});

const loadRoles = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm,
    };
    const data = await getRoleList(params);
    roleList.value = data.list || [];
    pagination.total = data.total || 0;
  } catch (error) {
    ElMessage.error("获取角色列表失败");
  } finally {
    loading.value = false;
  }
};

const handleSearch = (params) => {
  Object.assign(searchForm, params);
  pagination.current = 1;
  loadRoles();
};

const handleReset = (params) => {
  Object.assign(searchForm, params);
  pagination.current = 1;
  loadRoles();
};

const handleAdd = () => {
  currentRole.value = null;
  dialogVisible.value = true;
};

const handleEdit = (row) => {
  currentRole.value = { ...row };
  dialogVisible.value = true;
};

const handleAssignMenus = (row) => {
  currentRole.value = { ...row };
  menuDialogVisible.value = true;
};

const handleCommand = async (command, row) => {
  switch (command) {
    case "toggleStatus":
      await handleToggleStatus(row);
      break;
    case "delete":
      await handleDelete(row);
      break;
  }
};

const handleToggleStatus = async (row) => {
  try {
    const newStatus = !row.status;
    await updateRoleStatus(row.id, newStatus);
    ElMessage.success(`${newStatus ? "启用" : "禁用"}成功`);
    loadRoles();
  } catch (error) {
    ElMessage.error("状态更新失败");
  }
};

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm("确定要删除该角色吗？", "提示");
    await deleteRole(row.id);
    ElMessage.success("删除成功");
    loadRoles();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
};

const handleSizeChange = (val) => {
  pagination.pageSize = val;
  loadRoles();
};

const handleCurrentChange = (val) => {
  pagination.current = val;
  loadRoles();
};

const handleSuccess = () => {
  dialogVisible.value = false;
  loadRoles();
};

const handleMenuAssignSuccess = () => {
  menuDialogVisible.value = false;
  loadRoles();
};

onMounted(() => {
  loadRoles();
});
</script>

<style scoped>
/* 使用Tailwind CSS替代原有样式 */
</style>